package com.sss.myspringsecurity.config.websocketconfig.stomp;

import org.springframework.context.ApplicationListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.web.socket.messaging.SessionConnectEvent;

import java.util.concurrent.ConcurrentHashMap;

/**
 * websocket 监听器
 * @author sss
 * @date 2020-02-17 11:08
 **/
public class STOMPConnectEventListener implements ApplicationListener<SessionConnectEvent> {

    private ConcurrentHashMap<String,Object> userSession=new ConcurrentHashMap<>();
    private String userId="";

    @Override
    public void onApplicationEvent(SessionConnectEvent event) {
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(event.getMessage());
        //login get from browser
        if(accessor.getNativeHeader("token")==null){
            return;
        }

        String userid = accessor.getNativeHeader("token").get(0);
        userId=userid;
        String sessionId = accessor.getSessionId();
        userSession.put(userid,sessionId);
    //    redisHelper.redisTemplate.opsForValue().set("websocket:"+userid,sessionId);
    }

    public String getUserSession(){
        return (String) userSession.get(userId);
    }
}
